//
//  YLLabel.swift
//  GLUZSwift
//
//  Created by xyanl on 2025/4/17.
//

import UIKit

enum YLTextAlignment {
    /// 默认: 左上
    case normal
    
    case leftTop
    case leftCenter
    case leftBottom
    
    case centerTop
    case center
    case centerBottom
    
    case rightTop
    case rightCenter
    case rightBottom
    
}

class YLLabel: UILabel {
    
    var alignment: YLTextAlignment = .normal
    
    // 用来改变label里面文字展示窗口的大小，你可以自己根据文字的多少，来计算窗口的大小
    override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect {
        var textRect = super.textRect(forBounds: bounds, limitedToNumberOfLines: numberOfLines)
        
        switch alignment {
        case .normal, .leftTop:
            textRect.origin.x = bounds.origin.x
            textRect.origin.y = bounds.origin.y
            
        case .leftCenter:
            textRect.origin.x = bounds.origin.x
            textRect.origin.y = (bounds.size.height - textRect.size.height)*0.5
            
        case .leftBottom:
            textRect.origin.x = bounds.origin.x
            textRect.origin.y = bounds.size.height - textRect.size.height
            
        case .centerTop:
            textRect.origin.x = (bounds.size.width - textRect.size.width)*0.5
            textRect.origin.y = bounds.origin.y
            
        case .center:
            textRect.origin.x = (bounds.size.width - textRect.size.width)*0.5
            textRect.origin.y = (bounds.size.height - textRect.size.height)*0.5
            
        case .centerBottom:
            textRect.origin.x = (bounds.size.width - textRect.size.width)*0.5
            textRect.origin.y = bounds.size.height - textRect.size.height
            
        case .rightTop:
            textRect.origin.x = bounds.size.width - textRect.size.width
            textRect.origin.y = bounds.origin.y
            
        case .rightCenter:
            textRect.origin.x = bounds.size.width - textRect.size.width
            textRect.origin.y = (bounds.size.height - textRect.size.height)*0.5
            
        case .rightBottom:
            textRect.origin.x = bounds.size.width - textRect.size.width
            textRect.origin.y = bounds.size.height - textRect.size.height
            
        }
        
        return textRect
    }
    
    
    // 改变绘文字属性.重写时调用super可以按默认图形属性绘制,若自己完全重写绘制函数，就不用调用super了.
    override func drawText(in rect: CGRect) {
        let actualRect = textRect(forBounds: rect, limitedToNumberOfLines: numberOfLines)
        super.drawText(in: actualRect)
    }
}
